package com.tj.jinzao.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.bumptech.glide.Glide;
import com.tj.jinzao.BuildConfig;
import com.tj.jinzao.R;
import com.tj.jinzao.common.Constant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ImageSwitch which supports swipe and click gestures.
 */
@SuppressWarnings("UnusedDeclaration")
public class MyImageSwitcher extends ImageSwitcher
        implements ViewSwitcher.ViewFactory/*, ImageResizer.InSampleSizeCalculator*/ {
    private final static String TAG = BuildConfig.TAG_PREFIX + "MyImageSwitcher";

    public static final int IMAGE_SWITCH_DELAY_MILLIS = 3000;

    public final static int IMAGE_SOURCE_TYPE_URI = 0;
    public final static int IMAGE_SOURCE_TYPE_DRAWABLE = 1;
    public final static int IMAGE_SOURCE_TYPE_RESOURCE = 2;
    public final static int IMAGE_SOURCE_TYPE_URL = 3;

    private Handler mHandler;
    private Runnable mSwitchImageRunnable;
    private boolean mStop;

    private int mSwitchInterval = IMAGE_SWITCH_DELAY_MILLIS;

    private List<?> mImages;
    private int mPos;
    private int mImageSourceType;

    private int mLastX, mLastY;

    private float mMoveX, mMoveY;

    private OnClickListener mOnClickListener;
    private OnChangeListener mOnChangeListener;
    private OnRefreshListener mOnRefreshListener;
    private OnConflictListener mOnConflictListener;

    private int mWidth, mHeight;
    private boolean mForceSetImage = true;

    private boolean mInterceptTouchEvent = true;

    private ImageView.ScaleType mScaleType;

    private boolean mShowIndicator = false;

    private int mDotRadius, mRightMargin;

    private LinearLayout mDotLayout;

    public MyImageSwitcher(Context context) {
        this(context, null);
    }

    public MyImageSwitcher(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyImageSwitcher, 0, 0);
        int index = a.getInt(R.styleable.MyImageSwitcher_android_scaleType, -1);
        a.recycle();
        if (index >= 0) {
            mScaleType = ImageView.ScaleType.values()[index];
        } else {
            mScaleType = ImageView.ScaleType.FIT_XY;
        }
        setFactory(this);

        mHandler = new Handler();
        mSwitchImageRunnable = new Runnable() {
            @Override
            public void run() {
                if (mStop) return;
                if (mImages != null && mImages.size() != 1) {
                    if (mPos >= mImages.size() - 1) mPos = -1;
                    setImage(++mPos);
                    onPageSelect(mPos);
                    if (mSwitchInterval >= 0) {
                        mHandler.postDelayed(mSwitchImageRunnable, mSwitchInterval);
                    }
                }

            }
        };
        mDotRadius = (int) (12 * Constant.SCALE_X);
    }

    public void setImages(List<?> images) {
        if (images != null) {
            setImages(images, mPos < images.size() ? mPos : 0);
        }
    }

    /**
     * Set the images for the ImageSwitcher to display.
     */
    public void setImages(List<?> images, int index) {
        mPos = index;
        mImages = images;
        Object o = images.get(index);
        if (o instanceof Uri) mImageSourceType = IMAGE_SOURCE_TYPE_URI;
        else if (o instanceof Drawable) mImageSourceType = IMAGE_SOURCE_TYPE_DRAWABLE;
        else if (o instanceof String) mImageSourceType = IMAGE_SOURCE_TYPE_URL;
        else mImageSourceType = IMAGE_SOURCE_TYPE_RESOURCE;
        setImage(index);
        setDot();
        setVisibility(VISIBLE);
    }

    private void setDot() {
        if (mDotLayout == null) return;
        mDotLayout.removeAllViews();
        int size = mImages.size();
        if (mShowIndicator && size > 1) {
            for (int i = 0; i < size; i++) {
                View dot = new View(getContext());
                LinearLayout.LayoutParams params;
                if (mDotWidth != 0 && mDotHeight != 0) {
                    params = new LinearLayout.LayoutParams(mDotWidth, mDotHeight);
                } else {
                    params = new LinearLayout.LayoutParams(mDotRadius, mDotRadius);
                }
                params.gravity = Gravity.CENTER;
                if (i != size - 1) {
                    params.rightMargin = mRightMargin == 0 ? mDotRadius : mRightMargin;//指定右边距
                }
                dot.setLayoutParams(params);//设置布局参数
                dot.setBackgroundResource(R.drawable.bg_article_image_point);
                dot.setActivated(i == 0 ? true : false);
                mDotLayout.addView(dot);
                //view设置唯一标示
                dot.setTag(i);
            }
        }
    }

    private void onPageSelect(int pos) {
        if (mShowIndicator && mDotLayout != null) {
            int length = mDotLayout.getChildCount();
            for (int i = 0; i < length; i++) {
                View dot = mDotLayout.getChildAt(i);
                dot.setActivated(i == pos ? true : false);
            }
        }
        if (mTitleTv != null && mTitles != null) {
            if (pos < mTitles.size()) {
                mTitleTv.setText(mTitles.get(pos));
            }
        }
        if (mOnChangeListener != null) mOnChangeListener.OnPageSelected(pos);
    }

    public void setImages(Uri[] images) {
        setImages(images, 0);
    }

    public void setImages(Uri[] images, int index) {
        setImages(Arrays.asList(images), index);
    }

    /**
     * 用于显示下标
     *
     * @param dotLayout
     */
    public void setDotLayout(LinearLayout dotLayout) {
        this.mDotLayout = dotLayout;
    }

    public void setShowIndicator(boolean showIndicator) {
        this.mShowIndicator = showIndicator;
    }

    /**
     * Specify the animation used to flip images animate a View that enters the screen.
     *
     * @param inAnimationResId  The animation started when a View enters the screen.
     * @param outAnimationResId The animation started when a View exits the screen.
     */
    public void setAnimations(int inAnimationResId, int outAnimationResId) {
        Context context = getContext();
        if (null != context) {
            setInAnimation(AnimationUtils.loadAnimation(context, inAnimationResId));
            setOutAnimation(AnimationUtils.loadAnimation(context, outAnimationResId));
        }
    }

    /**
     * Register a callback to be invoked when this view is clicked.
     *
     * @param l The callback that will run
     */
    public void setOnClickListener(OnClickListener l) {
        mOnClickListener = l;
    }

    public void setOnChangeListener(OnChangeListener l) {
        mOnChangeListener = l;
    }

    public void setOnRefreshListener(OnRefreshListener l) {
        mOnRefreshListener = l;
    }

    public void setOnConflictListener(OnConflictListener l) {
        mOnConflictListener = l;
    }

    public void setInterceptTouchEvent(boolean isIntercept) {
        this.mInterceptTouchEvent = isIntercept;
    }

    /**
     * Set the time we wait before showing the next image.
     *
     * @param interval Time in milliseconds. The default interval is 3 seconds.
     */
    public void setSwitchInterval(int interval) {
        if (interval != mSwitchInterval) mSwitchInterval = interval;
    }

    /**
     * Start flipping images. Please call this on Activity's onResume().
     */
    public void dispatchOnResume() {
        if (mSwitchInterval >= 0
                && null != mImages && mImages.size() > 1 && null != getWindowToken()) {
            mStop = false;
            mHandler.removeCallbacks(mSwitchImageRunnable);
            mHandler.postDelayed(mSwitchImageRunnable, mSwitchInterval);
        }
    }

    /**
     * Stop flipping images. Please call this on Activity's onPause().
     */
    public void dispatchOnPause() {
        mStop = true;
        mHandler.removeCallbacks(mSwitchImageRunnable);
    }

    public void setImage(int pos) {
        if (mWidth <= 0 || mHeight <= 0) return;

        try {
            switch (mImageSourceType) {
                case IMAGE_SOURCE_TYPE_URI: {
                    Uri uri = (Uri) mImages.get(pos);
                    String t = uri.toString();
                    Glide.with(getContext()).load(t).into((ImageView) getNextView());
                    break;
                }
                case IMAGE_SOURCE_TYPE_URL: {
                    String t = (String) mImages.get(pos);
                    Glide.with(getContext()).load(t).into((ImageView) getNextView());
                    break;
                }
                case IMAGE_SOURCE_TYPE_DRAWABLE:
                    Glide.with(getContext()).load((Drawable) mImages.get(pos)).into((ImageView) getNextView());
                    break;
                case IMAGE_SOURCE_TYPE_RESOURCE: {
                    int res = (Integer) mImages.get(pos);
                    Glide.with(getContext()).load(res).into((ImageView) getNextView());
                    break;
                }
            }
            showNext();
        } catch (Exception ignored) {
        }
    }

    public void setImageDrawable(Drawable drawable) {
        ((ImageView) getNextView()).setImageDrawable(drawable);
        showNext();
    }

    @Override
    public View makeView() {
        ImageView image = new ImageView(getContext());
        image.setLayoutParams(new LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT));
        image.setScaleType(mScaleType);
        return image;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean result = super.dispatchTouchEvent(ev);
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        final int action = ev.getAction();
        boolean flingConfirmed = false;
        int prevPos = mPos;
        switch (action & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN: {
                if (mOnRefreshListener != null) mOnRefreshListener.OnRefreshed(false);
                mMoveX = mMoveY = 0;
                mLastX = (int) ev.getRawX();
                mLastY = (int) ev.getRawY();
                if (mInterceptTouchEvent) {
                    try {
                        //应该是受到SwipeRefreshLayout的影响导致拦截父控件无效
                        if (mOnConflictListener != null) mOnConflictListener.OnConflicted(true);
                        getParent().requestDisallowInterceptTouchEvent(true);
                    } catch (NullPointerException ignored) {
                    }
                    break;
                }
            }
            return super.onTouchEvent(ev);
            case MotionEvent.ACTION_MOVE:
                mMoveX = Math.abs(ev.getRawX() - mLastX);
                mMoveY = Math.abs(ev.getRawY() - mLastY);
                if (mMoveX > mMoveY) {
                    return true;
                } else {
                    if (mOnRefreshListener != null)
                        mOnRefreshListener.OnRefreshed(mMoveY < 5 ? false : true);
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if (mOnRefreshListener != null) mOnRefreshListener.OnRefreshed(true);
                if (ev.getRawX() - mLastX > 30f) {
                    // Right swipe, show the left item
                    flingConfirmed = true;
                    if (--mPos < 0) {
                        mPos = mImages.size() - 1;
                    }
                    onPageSelect(mPos);
                } else if (ev.getRawX() - mLastX < -30f) {
                    // Left swipe, show the right item
                    flingConfirmed = true;
                    if (++mPos > mImages.size() - 1) {
                        mPos = 0;
                    }
                    onPageSelect(mPos);
                }
                if (!flingConfirmed) {
                    if (mMoveY < 5 && mMoveX < 5 && null != mOnClickListener) {
                        mOnClickListener.onClick(this);
                    }
                } else if (mPos != prevPos) {
                    mHandler.removeCallbacks(mSwitchImageRunnable);
                    setImage(mPos);
                    if (mSwitchInterval >= 0) {
                        mHandler.postDelayed(mSwitchImageRunnable, mSwitchInterval);
                    }
                }
                if (mInterceptTouchEvent) {
                    try {
                        //还原父控件事件
                        if (mOnConflictListener != null) mOnConflictListener.OnConflicted(false);
                        getParent().requestDisallowInterceptTouchEvent(false);
                    } catch (NullPointerException ignored) {
                    }
                }

                break;
        }
        if (mInterceptTouchEvent || flingConfirmed) {
            return true;
        } else {
            return super.onTouchEvent(ev);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (Constant.TRACE) {
            Log.d(TAG, "ImageSwitcher attached to window");
        }
        mForceSetImage = true;
    }

    @Override
    protected void onDetachedFromWindow() {
        dispatchOnPause();
        super.onDetachedFromWindow();
    }

    public int getPosition() {
        return mPos;
    }

    /*private int mMaxTextureSize;

    @Override
    public int calc(BitmapFactory
            .Options options, int reqWidth, int reqHeight, boolean aggressiveSample) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        if ((height >= reqHeight && width >= reqWidth)
                || !Build.BRAND.equalsIgnoreCase("xiaomi")) {
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Calling ImageResizer.calculateInSampleSize()...");
            }
            return ImageResizer.calculateInSampleSize(
                    options, reqWidth, reqHeight, aggressiveSample);
        } else {
            // On Xiaomi:
            // OpenGLRenderer: Bitmap too large to be uploaded into a texture (220x5528, max=4096x4096)
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "Calling InSampleSizeCalculator.calc()...");
            }
            int largeSide = Math.max(height, width);
            int N = 1;
            if (mMaxTextureSize <= 0) {
                int[] maxTextureSize = new int[1];
                GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0);
                mMaxTextureSize = maxTextureSize[0];
                Trace.i(TAG, "Max texture size: " + mMaxTextureSize);
            }
            while (largeSide / N > mMaxTextureSize) {
                N *= 2;
            }
            if (QiiGameLib.TRACE) {
                Trace.w(TAG, "Bitmap size: " + height + '*' + width
                        + ", request: " + reqHeight + '*' + reqWidth + "; inSampleSize: " + N);
            }
            return N;
        }
    }*/

    public interface OnChangeListener {
        void OnPageSelected(int position);
    }

    public interface OnRefreshListener {
        void OnRefreshed(boolean isRefresh);
    }

    public interface OnConflictListener {
        void OnConflicted(boolean isConflict);
    }

    private static float SCALE = 720.f / 400;

    public void setScale(float index) {
        SCALE = index / 400;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (Constant.TRACE) {
            Log.d(TAG, "ImageSwitcher width: "
                    + getMeasuredWidth() + ", height: " + getMeasuredHeight()
                    + " desired width: " + mWidth + ", desired height: " + mHeight);
        }
        if (mWidth <= 0 || mHeight <= 0) {
            if (mWidth <= 0) mWidth = getMeasuredWidth();
            if (mHeight <= 0) mHeight = getMeasuredHeight();
        } else if (!mForceSetImage) {
            return;
        }
        mForceSetImage = false;

        setImage(mPos);
        dispatchOnResume();
    }

    @Override
    public void setLayoutParams(ViewGroup.LayoutParams params) {
        if (params.width == -1) {
            if (mNewHeight == 0) {
                if (params.height != 100) {
                    try {
                        Log.d(TAG, "ImageSwitcher layout params.scale: "
                                + SCALE + ", height: " + mHeight);
                        int newHeight = (int) (getContext().getResources().getDisplayMetrics().widthPixels / SCALE);
                        params.height = newHeight;
                    } catch (Exception e) {
                    }
                } else {
                    try {
                        Log.d(TAG, "ImageSwitcher layout params.scale: "
                                + SCALE + ", height: " + mHeight);
                        int newHeight = (int) (getContext().getResources().getDisplayMetrics().widthPixels / (820.f / 400));
                        params.height = newHeight;
                    } catch (Exception e) {
                    }
                }
            } else {
                params.height = mNewHeight;
            }
        }

        super.setLayoutParams(params);
        mWidth = params.width;
        if (mWidth == -1) {
            mWidth = Constant.SCREEN_WIDTH;
        }
        mHeight = params.height;

        if (Constant.TRACE) {
            Log.d(TAG, "ImageSwitcher layout params.width: "
                    + mWidth + ", height: " + mHeight);
        }
    }

    //add the method to get the width and height of the imageswitcher currently
    public int getCurrentWidth() {
        return mWidth;
    }

    public int getCurrentHeight() {
        return mHeight;
    }


    public void setDotParams(int radius, int rightMargin) {
        mDotRadius = radius;
        mRightMargin = rightMargin;
    }

    private int mDotWidth, mDotHeight;

    public void setDotParams(int width, int height, int rightMargin) {
        mDotWidth = width;
        mDotHeight = height;
        mRightMargin = rightMargin;
    }

    private TextView mTitleTv;

    public void setTitleLayout(TextView textView) {
        mTitleTv = textView;
    }

    private ArrayList<String> mTitles;

    public void setImages(List<?> images, ArrayList<String> titles, int index) {
        mPos = index;
        mImages = images;
        mTitles = titles;
        Object o = images.get(index);
        if (o instanceof Uri) mImageSourceType = IMAGE_SOURCE_TYPE_URI;
        else if (o instanceof Drawable) mImageSourceType = IMAGE_SOURCE_TYPE_DRAWABLE;
        else if (o instanceof String) mImageSourceType = IMAGE_SOURCE_TYPE_URL;
        else mImageSourceType = IMAGE_SOURCE_TYPE_RESOURCE;
        setImage(index);
        setDot();
        setVisibility(VISIBLE);
        if (mTitleTv != null && mTitles != null && mTitles.size() > 0) {
            mTitleTv.setText(mTitles.get(0));
        }
    }

    private int mNewHeight;

    public void setHeight(int height) {

        mNewHeight = height;

        setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height));
    }

    public boolean getStopState(){
        return mStop;
    }
}
